package com.example.es.create;

import com.example.es.api.ESClient;
import com.example.es.api.ESConfig;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.hamcrest.CoreMatchers.*;

import static  org.junit.Assert.assertThat;
/**
 * Created by yanlei on 2017/7/9.
 */
@RunWith(JUnit4.class)
public class IndexCreate {
    private ESClient esClient  = null;
    private String index="person";
    private String type="man";
    private String id = "10000101";


    public ESClient getEsClient() {
        return esClient;
    }

    public void setEsClient(ESClient esClient) {
        this.esClient = esClient;
    }
    public String   create(){
        String json="{\"name\":\"yanlei\", \"age\":37, \"birthday\":\"19801117\", \"sex\":\"man\"}";
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index(index).type(type).id(id).source(json, XContentType.JSON).create(true);
        IndexResponse response = this.getEsClient().index(indexRequest);
        String id = response.getId();
        return id;
    }
    public void   get(String id){
        String json="{\"name\":\"yanlei\", \"age\":37, \"birthday\":\"19801117\", \"sex\":\"man\"}";
        GetRequest getRequest = new GetRequest();
        getRequest.index(index).type(type).id(id);
        GetResponse getResponse = this.getEsClient().get(getRequest);
        String source = getResponse.getSourceAsString();
        System.out.print(source);
        assertThat(source, equalTo(json));

    }

    public void query(){

    }

    public void modify(){

    }
    @Test
    public  void test(){
        String id = create();
        get(id);
    }

    @Before
    public  void  before(){
        ESConfig esConfig = new ESConfig();
        ESClient esClient = new ESClient();
        esClient.setEsConfig(esConfig);
        this.setEsClient(esClient);
    }
    @After
    public  void after(){
        this.esClient.close();
    }

    public static void main(String args []){
        IndexCreate indexCreate = new IndexCreate();
        System.out.println("start test.....");
        indexCreate.before();
        indexCreate.test();
        indexCreate.after();
    }
}
